/**
 * Copyright (c) 2009, http://www.softwareinlife.com. All rights reserved.
 * 
 * Redistribution and use in source and binary forms, 
 * with or without modification, are permitted provided that 
 * the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the above copyright notice, 
 *    this list of conditions and the following disclaimer.
 * 
 * 2. Redistributions in binary form must reproduce the above copyright notice, 
 *    this list of conditions and the following disclaimer in the documentation 
 *    and/or other materials provided with the distribution.
 * 
 * 3. Neither the name of the http://www.softwareinlife.com nor the names of its 
 *    contributors may be used to endorse or promote products derived from 
 *    this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE SOFTWAREINLIFE AND CONTRIBUTORS "AS IS" 
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
 * ARE DISCLAIMED. 
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.softwareinlife.vision.android.ux.schedule;

import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;

import com.softwareinlife.vision.android.R;
import com.softwareinlife.vision.android.data.dao.ScheduleDAO;
import com.softwareinlife.vision.android.data.exceptions.DatabaseConnectionException;
import com.softwareinlife.vision.android.data.exceptions.ScheduleCreateException;
import com.softwareinlife.vision.android.data.model.PlanModel;
import com.softwareinlife.vision.android.data.model.ScheduleModel;
import com.softwareinlife.vision.android.system.util.StringUtil;
import com.softwareinlife.vision.android.ux.util.SharedPreferenceUtility;

public class CreateScheduleActivity extends Activity {

	protected static final int START_TIME_DIALOG = 1;

	protected static final int START_DATE_DIALOG = 2;

	protected static final int END_DATE_DIALOG = 3;

	protected static final int END_TIME_DIALOG = 4;

	/**
	 * Plan Model
	 */
	private PlanModel plan = null;

	// Member Variables //////////////////////////////

	/**
	 * Schedule Plan Title Text View
	 */
	private TextView schedulePlanTitleTextView = null;

	/**
	 * Title Text View
	 */
	private EditText titleEditText = null;

	/**
	 * Statement Edit Text
	 */
	private EditText statementEditText = null;

	// START Time //////////////////////////////////

	/**
	 * Time of Start
	 */
	private Date startDate = null;

	/**
	 * TextView of Start Time
	 */
	private TextView startTimeTextView = null;

	/**
	 * Button for Start Date Picker
	 */
	private Button startDatePickerButton = null;

	/**
	 * Click Listener for Start Date
	 */
	protected OnClickListener startDateClickListener = null;

	/**
	 * Date Select Listener for Start Date
	 */
	protected OnDateSetListener startDateSelectListener = null;

	/**
	 * Button for Start Time Picker
	 */
	private Button startTimePickerButton = null;

	/**
	 * Click Listener for Start Time
	 */
	protected OnClickListener startTimeClickListener = null;

	/**
	 * Date Select Listener for Start Time
	 */
	protected OnTimeSetListener startTimeSelectListener = null;

	// END Time ///////////////////////////////////
	/**
	 * Time of End
	 */
	private Date endDate = null;

	/**
	 * TextView of End Time
	 */
	private TextView endTimeTextView = null;

	/**
	 * Button for End Date Picker
	 */
	private Button endDatePickerButton = null;

	/**
	 * Click Listener for End Date
	 */
	protected OnClickListener endDateClickListener = null;

	/**
	 * Date Select Listener for End Date
	 */
	protected OnDateSetListener endDateSelectListener = null;

	/**
	 * Button for Start Time Picker
	 */
	private Button endTimePickerButton = null;

	/**
	 * Click Listener for End Time
	 */
	protected OnClickListener endTimeClickListener = null;

	/**
	 * Date Select Listener for End Time
	 */
	protected OnTimeSetListener endTimeSelectListener = null;

	// CREATE BUTTON /////////////////////////////////////

	/**
	 * Button of Create
	 */
	private Button createButton = null;

	/**
	 * Click Listener for Create Button
	 */
	private OnClickListener createButtonClickListener = null;

	// CANCEL BUTTON /////////////////////////////////////

	/**
	 * Button of Cancel
	 */
	private Button cancelButton = null;

	/**
	 * Click Listener for Create Button
	 */
	private OnClickListener cancelButtonClickListener = null;

	private Calendar calendar = null;

	/**
	 * Constructor
	 */
	public CreateScheduleActivity() {
		super();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Load Data
		loadData();

		// Set View
		setContentView(R.layout.schedule_create);

		// Initialize Members
		initMemembers();

		// Initialize Actions
		initActions();
	}

	/**
	 * Initialize Members
	 */
	private void initMemembers() {
		// Calendar
		calendar = Calendar.getInstance();
		startDate = new Date();
		endDate = new Date();

		// Schedule Plan Title Text View
		schedulePlanTitleTextView = (TextView) findViewById(R.id.schedulePlanTitleTextView);
		schedulePlanTitleTextView.setText("(" + plan.getTitle() + ")");

		// Title
		titleEditText = (EditText) findViewById(R.id.titleEditText);

		// Statement
		statementEditText = (EditText) findViewById(R.id.statmentEditText);

		// Start Time
		startTimeTextView = (TextView) findViewById(R.id.startDateTextView);

		// Start Date Button
		startDatePickerButton = (Button) findViewById(R.id.startDatePickerButton);

		// Start Time Button
		startTimePickerButton = (Button) findViewById(R.id.startTimePickerButton);

		// End Time
		endTimeTextView = (TextView) findViewById(R.id.endDateTextView);

		// End Date Button
		endDatePickerButton = (Button) findViewById(R.id.endDatePickerButton);

		// End Time Button
		endTimePickerButton = (Button) findViewById(R.id.endTimePickerButton);

		// Create Button
		createButton = (Button) findViewById(R.id.createButton);

		// Cancel Button
		cancelButton = (Button) findViewById(R.id.cancelButton);
	}

	/**
	 * Initialize Actions
	 */
	private void initActions() {

		// Start Time/////////////////////////////////////
		startDateSelectListener = new OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				// Calendar
				Calendar cal = Calendar.getInstance();

				cal.setTimeInMillis(startDate.getTime());

				cal.set(Calendar.YEAR, year);
				cal.set(Calendar.MONTH, monthOfYear);
				cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);

				startDate = cal.getTime();

				updateDateAndTime();
			}
		};

		startDateClickListener = new OnClickListener() {
			public void onClick(View v) {
				onCreateDialog(START_DATE_DIALOG);
			}
		};

		startDatePickerButton.setOnClickListener(startDateClickListener);

		startTimeSelectListener = new OnTimeSetListener() {
			public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
				// Calendar
				Calendar cal = Calendar.getInstance();

				cal.setTimeInMillis(startDate.getTime());

				cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
				cal.set(Calendar.MINUTE, minute);

				startDate = cal.getTime();

				updateDateAndTime();
			}
		};

		startTimeClickListener = new OnClickListener() {
			public void onClick(View v) {
				onCreateDialog(START_TIME_DIALOG);
			}
		};

		startTimePickerButton.setOnClickListener(startTimeClickListener);

		// End Time/////////////////////////////////////
		endDateSelectListener = new OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				// Calendar
				Calendar cal = Calendar.getInstance();

				cal.setTimeInMillis(endDate.getTime());

				cal.set(Calendar.YEAR, year);
				cal.set(Calendar.MONTH, monthOfYear);
				cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);

				endDate = cal.getTime();

				updateDateAndTime();
			}
		};

		endDateClickListener = new OnClickListener() {
			public void onClick(View v) {
				onCreateDialog(END_DATE_DIALOG);
			}
		};

		endDatePickerButton.setOnClickListener(endDateClickListener);

		endTimeSelectListener = new OnTimeSetListener() {
			public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
				// Calendar
				Calendar cal = Calendar.getInstance();

				cal.setTimeInMillis(endDate.getTime());

				cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
				cal.set(Calendar.MINUTE, minute);

				endDate = cal.getTime();

				updateDateAndTime();
			}
		};

		endTimeClickListener = new OnClickListener() {
			public void onClick(View v) {
				onCreateDialog(END_TIME_DIALOG);
			}
		};

		endTimePickerButton.setOnClickListener(endTimeClickListener);

		// CREATE BUTTON //////////////////////////////////
		createButtonClickListener = new OnClickListener() {
			public void onClick(View v) {
				try {
					createScheduleHandler();
				} catch (ScheduleCreateException e) {
					e.printStackTrace();
				}

				changeScheduleListScreen();
			}
		};

		createButton.setOnClickListener(createButtonClickListener);

		// CANCEL BUTTON //////////////////////////////////
		cancelButtonClickListener = new OnClickListener() {
			public void onClick(View v) {

				changeScheduleListScreen();
			}
		};

		cancelButton.setOnClickListener(cancelButtonClickListener);
	}

	/**
	 * Display Start Time(default / button click)
	 */
	protected void updateDateAndTime() {
		startTimeTextView.setText(StringUtil.toString(startDate));

		endTimeTextView.setText(StringUtil.toString(endDate));
	}

	/**
	 * Change Vision List Screen
	 */
	protected void changeScheduleListScreen() {
		Intent intent = new Intent(this, ReadScheduleActivity.class);
		startActivity(intent);
	}

	/**
	 * Create Vision Handler
	 * 
	 * @throws ScheduleCreateException
	 * 
	 */
	protected void createScheduleHandler() throws ScheduleCreateException {
		try {
			// Create Model
			ScheduleModel model = new ScheduleModel();
			model.setTitle(titleEditText.getText().toString());
			model.setDesc(statementEditText.getText().toString());
			model.setStartDate(startDate);
			model.setEndDate(endDate);
			model.setPlan(SharedPreferenceUtility
					.getPlanModel(getApplication()));
			model.setUser(SharedPreferenceUtility
					.getUserModel(getApplicationContext()));

			// Now
			Date now = new Date();
			model.setCreatedDate(now);
			model.setModifiedDate(now);

			// Create DAO
			ScheduleDAO dao = new ScheduleDAO(getApplicationContext());

			// Create Operation
			dao.create(model);

		} catch (DatabaseConnectionException dce) {
			dce.printStackTrace();

		} catch (ScheduleCreateException vce) {
			vce.printStackTrace();

		}
	}

	/**
	 * (first setting time & button event time) of TimePicker
	 */
	@Override
	protected Dialog onCreateDialog(int id) {

		Dialog dialog = null;

		// Start Calendar
		Calendar startCal = Calendar.getInstance();
		startCal.setTime(startDate);

		// End Calendar
		Calendar endCal = Calendar.getInstance();
		endCal.setTime(endDate);

		switch (id) {

		case START_DATE_DIALOG:
			dialog = new DatePickerDialog(this, startDateSelectListener,
					startCal.get(Calendar.YEAR), startCal.get(Calendar.MONTH),
					startCal.get(Calendar.DAY_OF_MONTH));
			break;

		case START_TIME_DIALOG:
			dialog = new TimePickerDialog(this, startTimeSelectListener,
					startCal.get(Calendar.HOUR_OF_DAY), startCal
							.get(Calendar.MINUTE), true);
			break;

		case END_DATE_DIALOG:
			dialog = new DatePickerDialog(this, endDateSelectListener, endCal
					.get(Calendar.YEAR), endCal.get(Calendar.MONTH), endCal
					.get(Calendar.DAY_OF_MONTH));
			break;

		case END_TIME_DIALOG:
			dialog = new TimePickerDialog(this, endTimeSelectListener, endCal
					.get(Calendar.HOUR_OF_DAY), endCal.get(Calendar.MINUTE),
					true);
			break;

		}

		dialog.show();

		return dialog;
	}

	/**
	 * Load List Data
	 */
	private void loadData() {
		// Get Plan
		plan = SharedPreferenceUtility.getPlanModel(getApplicationContext());
	}
}